package com.jutixueyuan.service.impl;

import com.jutixueyuan.pojo.Item;
import com.jutixueyuan.pojo.LivegoodsResult;
import com.jutixueyuan.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Value("${livegoods.fastdfs.nginx}")
    private String livegoodsFastDfsNginx;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public LivegoodsResult selectRecommendationByCity(String city) {

       try {
           
           //创建空条件
           Criteria criteriaBox = new Criteria();

           //城市条件
           Criteria criteria1 = Criteria.where("city").is(city);
           //热门条件
           Criteria criteria2 = Criteria.where("recommendation").is(true);

           //两个条件设置and关系
           criteriaBox.andOperator(criteria1,criteria2);

           Query query = new Query(criteriaBox);

           //分页
           query.with(PageRequest.of(0,4));

           //排序
           query.with(Sort.by(Sort.Order.desc("recoSort")));

           //执行查询
           List<Item> items = mongoTemplate.find(query, Item.class);

           for (Item item : items) {
               item.setImg(this.livegoodsFastDfsNginx+item.getImg());
           }

           //组装LivegoodsResult对象
           LivegoodsResult ok = LivegoodsResult.ok(items);

           return ok;
       }catch (Exception e){
           return LivegoodsResult.error("请求失败...");
       }



    }
}
